class Solution(object):
    def wallsAndGates(self, rooms):
        """
        :type rooms: List[List[int]]
        :rtype: None Do not return anything, modify rooms in-place instead.
        """
        m = len(rooms)
        n = len(rooms[0])
        already_set = set()
        search_set = set()
        for i in range(m):
            for j in range(n):
                if rooms[i][j] == 0:
                    search_set.add((i, j))

        def search(i, j):
            around = [[-1, 0], [1, 0], [0, -1], [0, 1]]
            for item in around:
                p = i + item[0]
                q = j + item[1]
                if 0 <= p < m and 0 <= q < n and rooms[p][q] >= 0 and (p, q) not in already_set and (
                p, q) not in search_set:
                    rooms[p][q] = rooms[i][j] + 1
                    next_set.add((p, q))

        while search_set:
            next_set = set()
            for item in search_set:
                search(item[0], item[1])
            already_set.update(search_set)
            search_set = next_set

        return rooms


data = Solution()
rooms = [[2147483647, -1, 0, 2147483647], [2147483647, 2147483647, 2147483647, -1], [2147483647, -1, 2147483647, -1],
         [0, -1, 2147483647, 2147483647]]
print(data.wallsAndGates(rooms))
rooms = [[0]]
print(data.wallsAndGates(rooms))
rooms = [[-1]]
print(data.wallsAndGates(rooms))
rooms = [[2147483647]]
print(data.wallsAndGates(rooms))